<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="90px">
            <el-form-item label="所属栏目:" prop="columnId" clearable>
                <treeselect v-model="queryParams.columnId" :options="columnOptions"
                            :show-count="true" placeholder="请选择归属咨询栏目" style="width: 200px;"/>
            </el-form-item>
            <el-form-item label="所属村社:" prop="communityId" clearable>
                <el-select v-model="queryParams.communityId" placeholder="请选择咨询展示的村社或村" width="100px">
                    <el-option
                        v-for="community in communityList"
                        :key="community.communityId"
                        :label="community.communityName"
                        :value="community.communityId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态:" prop="status" >
                <el-select v-model="queryParams.status" placeholder="是否显示" clearable>
                    <el-option
                        v-for="dict in dict.type.biz_yes_no"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="信息标题:" prop="title" clearable>
                <el-input
                    v-model="queryParams.title"
                    placeholder="请输入信息标题"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['docs:article:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="mpArticle"
                    v-hasPermi="['docs:article:add']"
                >获取公众号文章
                </el-button>
            </el-col>
<!--            <el-col :span="1.5">-->
<!--                <el-button-->
<!--                    type="danger"-->
<!--                    plain-->
<!--                    icon="el-icon-plus"-->
<!--                    size="mini"-->
<!--                    @click="handleAddOutLink"-->
<!--                    v-hasPermi="['docs:article:add']"-->
<!--                >新增外链信息-->
<!--                </el-button>-->
<!--            </el-col>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="ID" align="center" prop="articleId"/>
            <el-table-column label="村社-村" align="center" prop="communityName"/>
            <el-table-column label="栏目类别" align="center" prop="columnName"/>
            <el-table-column label="标题" align="center" prop="title" width="120px" :show-overflow-tooltip="true"/>
<!--            <el-table-column label="轮播展示" align="center" prop="isCarousel">-->
<!--                <template slot-scope="scope">-->
<!--                    <el-tag  v-if="scope.row.isCarousel == 1">是</el-tag>-->
<!--                    <el-tag  v-if="scope.row.isCarousel == 0">否</el-tag>-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column label="类型" align="center" prop="isCarousel">
                <template slot-scope="scope">
                    <el-tag  type="danger" v-if="scope.row.type == 1">外链</el-tag>
                    <el-tag  v-if="scope.row.type == 0">内部</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="阅读时间" align="center" prop="times">
                <template slot-scope="scope"><el-tag>{{scope.row.times}}s</el-tag></template>
            </el-table-column>
            <el-table-column label="奖励积分" align="center" prop="score">
                <template slot-scope="scope">
                    <el-tag  type="danger">{{scope.row.score}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="有效期" align="center"  width="200px;">
                <template slot-scope="scope">
                    <span>{{parseTime(scope.row.expireStart,'{y}-{m}-{d}')}} ~ {{parseTime(scope.row.expireEnd,'{y}-{m}-{d}')}}</span>
                </template>
            </el-table-column>
            <el-table-column label="阅读数" align="center" prop="visit"/>
            <!--<el-table-column label="分享数" align="center" prop="shares"/>-->
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['docs:article:edit']"
                    >修改
                    </el-button>

                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改栏目信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
                <el-form-item label="信息标题：" prop="title" style="width:600px">
                    <el-input v-model="form.title" placeholder="请输入信息标题"/>
                </el-form-item>
                <el-form-item label="发布栏目：" prop="columnId">
                    <treeselect v-model="form.columnId" :options="columnOptions" @select="treeSelectChange"
                                :show-count="true" placeholder="请选择归属咨询栏目"/>
                </el-form-item>
                <el-form-item label="显示村社：" prop="communityId">
                    <el-select v-model="form.communityId" placeholder="请选择咨询展示的村社或村" @change="changeCommunity">
                        <el-option
                            v-for="community in communityList"
                            :key="community.communityId"
                            :label="community.communityName"
                            :value="community.communityId"
                        ></el-option>
                    </el-select>
                </el-form-item>
<!--                <el-form-item label="轮播展示：" prop="carousel">-->
<!--                    <el-radio-group v-model="form.isCarousel">-->
<!--                        <el-radio :key="type.label" :label="type.label" v-for="type in carousels">{{ type.name }}</el-radio>-->
<!--                    </el-radio-group>-->
<!--                </el-form-item>-->
                <el-form-item label="查看人群：" prop="carousel">
                    <el-radio-group v-model="form.scope">
                        <el-radio :key="type.label" :label="type.label" v-for="type in partys">{{ type.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="咨询缩略图：" prop="imgUrl">
                    <image-upload v-model="form.imgUrl" :limit="1" :fileSize="1"/>
                </el-form-item>
                <el-form-item label="奖励积分：" prop="score">
                    <el-input v-model="form.score" placeholder="有效阅读奖励积分" style="width:300px"/>
                </el-form-item>
                <el-form-item label="阅读时间：" prop="times">
                    <el-input v-model="form.times" placeholder="有效阅读时间是多少秒" style="width:300px"/>
                </el-form-item>
                <el-form-item label="信息有效期：" prop="expireStart">
                    <el-col :span="20">
                        <el-date-picker
                            v-model="expireDate.date"
                            type="datetimerange"
                            range-separator="至"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            start-placeholder="有效期开始时间"
                            end-placeholder="有效期结束时间"  @change="expireDateFormat">
                        </el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="信息内容:" prop="content">
                    <editor v-model="form.content" :min-height="300" :fileSize="1" :type="url"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 添加或修改栏目信息对话框 -->
        <el-dialog :title="title" :visible.sync="outOpen" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="outRules" label-width="110px">
                <el-form-item label="信息标题：" prop="title" style="width:600px">
                    <el-input v-model="form.title" placeholder="请输入信息标题"/>
                </el-form-item>
                <el-form-item label="发布栏目：" prop="columnId">
                    <treeselect v-model="form.columnId" :options="columnOptions" @select="treeSelectChange"
                                :show-count="true" placeholder="请选择归属咨询栏目"/>
                </el-form-item>
                <el-form-item label="显示村社：" prop="communityId">
                    <el-select v-model="form.communityId" placeholder="请选择咨询展示的村社或村" @change="changeCommunity">
                        <el-option
                            v-for="community in communityList"
                            :key="community.communityId"
                            :label="community.communityName"
                            :value="community.communityId"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="轮播展示：" prop="carousel">
                    <el-radio-group v-model="form.isCarousel">
                        <el-radio :key="type.label" :label="type.label" v-for="type in carousels">{{ type.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="查看人群：" prop="carousel">
                    <el-radio-group v-model="form.scope">
                        <el-radio :key="type.label" :label="type.label" v-for="type in partys">{{ type.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="咨询缩略图：" prop="imgUrl">
                    <image-upload v-model="form.imgUrl" :limit="1" :fileSize="1"/>
                </el-form-item>
                <el-form-item label="奖励积分：" prop="score">
                    <el-input v-model="form.score" placeholder="有效阅读奖励积分" style="width:300px"/>
                </el-form-item>
                <el-form-item label="信息有效期：" prop="expireStart">
                    <el-col :span="20">
                        <el-date-picker
                            v-model="expireDate.date"
                            type="datetimerange"
                            range-separator="至"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            start-placeholder="有效期开始时间"
                            end-placeholder="有效期结束时间"  @change="expireDateFormat">
                        </el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="外部链接地址:" prop="outLink">
                    <el-input v-model="form.outLink" placeholder="请输入外部链接地址"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 获取外链 -->
        <el-dialog :title="mpTitle" :visible.sync="mpOpen" width="800px" append-to-body>
            <el-form ref="mp" :model="mpForm"  label-width="110px">
                <el-form-item label="文章地址:" prop="url">
                    <el-input v-model="mpForm.url" placeholder="请输入https://mp.weixin.qq.com/开头的文章地址"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="getMPArticle">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listArticle,
    getArticle,
    addArticle,
    updateArticle,
    columnTree,
    getMpArticle,
    changeArticleStatus
} from "@/api/docs/article";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listCommunity} from "@/api/organization/community";
import {changeColumnStatus} from "@/api/docs/column";

export default {
    name: "Article",
    dicts:['biz_yes_no','people_status'],
    components: {Treeselect},
    data() {
        return {
            mpTitle:'',
            mpForm:{},
            mpOpen:false,
            outOpen:false,
            expireDate:{
                date:[],
                expire_start:'',
                expire_end:'',
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 栏目信息表格数据
            articleList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            communityList:[],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                columnId: null,
                title: null,
            },
            querycommunityParams:{
                pageNum: 1,
                pageSize: 30,
                status:0
            },
            columnQueryParams:{
                pageNum: 1,
                pageSize: 10,
                columnType: 0
            },
            columnOptions: [],
            // 表单参数
            form: {"imgUrl": ""},
            carousels:[{'name':'否','label':0},{'name':'是','label':1}],
            partys:[{'name':'所有人','label':0},{'name':'仅党员','label':1}],
            // 表单校验
            rules: {
                title: [{required: true, message: "信息标题不能为空", trigger: "blur"}],
                communityId: [{required: true, message: "信息显示村社不能空", trigger: "blur"}],
                columnId: [{required: true, message: "信息显示的栏目", trigger: "blur"}],
                imgUrl: [{required: true, message: "信息缩略图不能空", trigger: "blur"}],
                expireStart: [{required: true, message: "信息有效期不能空", trigger: "blur"}],
                content: [{required: true, message: "信息内容不能为空", trigger: "blur"}],
                times: [{required: true, message: "阅读时间", trigger: "blur"}],
                score: [{required: true, message: "奖励积分", trigger: "blur"}],
            },
            outRules: {
                title: [{required: true, message: "信息标题不能为空", trigger: "blur"}],
                communityId: [{required: true, message: "信息显示村社不能空", trigger: "blur"}],
                columnId: [{required: true, message: "信息显示的栏目", trigger: "blur"}],
                imgUrl: [{required: true, message: "信息缩略图不能空", trigger: "blur"}],
                expireStart: [{required: true, message: "信息有效期不能空", trigger: "blur"}],
                outLink: [{required: true, message: "外链地址不能空", trigger: "blur"}],
                times: [{required: true, message: "阅读时间", trigger: "blur"}],
                score: [{required: true, message: "奖励积分", trigger: "blur"}],
            }
        };
    },
    created() {
        this.getList();
        this.getColumnTree();
        this.listCommunityOptions();
    },

    methods: {
        mpArticle:function (){
            this.mpOpen = true;
            this.mpTitle="尝试抓取公众号文章"
        },
        getMPArticle:function() {
            getMpArticle(this.mpForm).then(resp => {
                    this.handleAdd();
                    this.form.title = resp.data.title;
                    this.form.content = resp.data.content;
                    this.form.imgUrl = resp.data.imgUrl;
                    this.form.source = resp.data.source;
                    // this.open=false;
                this.mpOpen = false;
                this.mpForm = {};

            })
        },
        expireDateFormat(expire) {
            this.form.expireStart =expire[0].toString();
            this.form.expireEnd = expire[1].toString();
        },
        /** 查询栏目信息列表 */
        getColumnTree() {
            columnTree(0).then(response => {
                this.columnOptions = response.data;
                this.loading = false;
            });
        },
        listCommunityOptions() {
            listCommunity(this.querycommunityParams).then(resp => {
                this.communityList = resp.rows;
            })
        },
        getList() {
            this.loading = true;
            listArticle(this.queryParams).then(response => {
                this.articleList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.outOpen = false;
            this.outOpen = false;
            this.mpOpen = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.mp = {}
            this.form = {
                articleId: null,
                columnId: null,
                columnName: null,
                communityId: null,
                communityName: null,
                co: null,
                title: null,
                content: null,
                visit: null,
                shares: null,
                times: null,
                score: null,
                status: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                imgUrl: null,
                expireStart:null,
                expireEnd:null,
                isCarousel:0,
                scope:0,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.articleId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.form.type=0;
            this.open = true;
            this.title = "添加栏目信息";
            this.expireDate={}
        },
        handleAddOutLink:function () {
            this.reset();
            this.form.type=1;
            this.outOpen = true;
            this.title = "添加外链信息";
            this.expireDate={}
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const articleId = row.articleId || this.ids
            getArticle(articleId).then(response => {
                this.form = response.data;
                if (this.form.type==1) {
                    this.outOpen = true;
                    this.title = "修改外链信息";
                }
                else {
                    this.open = true;
                    this.title = "修改栏目信息";
                }
                this.expireDate.date = [];
                this.expireDate.date.push(response.data.expireStart);
                this.expireDate.date.push(response.data.expireEnd);
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.articleId != null) {
                        updateArticle(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.outOpen = false;
                            this.getList();
                        });
                    } else {
                        addArticle(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.outOpen = false;
                            this.getList();
                        });
                    }
                }
            });
        },

        /** 导出按钮操作 */
        handleExport() {
            this.download('docs/article/export', {
                ...this.queryParams
            }, `article_${new Date().getTime()}.xlsx`)
        },
        treeSelectChange(raw, instanceId) {
            if (raw.children != undefined && raw.children.length > 0) {
                this.$modal.alertError("请选择发布的子栏目");
            }
            this.form.columnName = raw.label;
        },
        changeCommunity(raw) {
            for (let communityListElement of this.communityList) { console.log(communityListElement)
                if(communityListElement.communityId==raw) {
                    this.form.communityName = communityListElement.communityName;
                    break;
                }
            }
            console.log(this.form.communityName)
        },
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "禁用";
            this.$modal.confirm('确认要' + text + row.title + '这个信息嘛？').then(function () {
                return changeArticleStatus(row.articleId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
    }
};
</script>
